﻿using CommunityToolkit.Mvvm.ComponentModel;
using CommunityToolkit.Mvvm.Input;
using CommunityToolkit.Mvvm.Messaging;
using MauiControl.Models;
using MauiControl.Services;
using System.Threading.Tasks;
using System.Windows.Input;

namespace MauiControl.ViewModels
{
    public partial class MainPageViewModel : ObservableObject
    {
        private readonly BluetoothService _bluetoothService;

        public MainPageViewModel(BluetoothService bluetoothService)
        {
            _bluetoothService = bluetoothService;
            SensorData = new SensorData(); // 初始化 SensorData 实例

            // 注册消息接收
            WeakReferenceMessenger.Default.Register<BleDeviceInfo>(this, (recipient, message) =>
            {
                ConnectedDevice = message;
            });

            // 初始化命令
            DisconnectCommand = new RelayCommand(Disconnect);
            ResetOffsetCommand = new RelayCommand(ResetOffset);

            // 开始读取传感器数据
            StartReadingSensorData();
        }

        [ObservableProperty]
        private BleDeviceInfo _connectedDevice;

        [ObservableProperty]
        private SensorData _sensorData; // 使用 ObservableProperty 自动生成属性

        // 断开连接命令
        public ICommand DisconnectCommand { get; }

        // 重置标点命令
        public ICommand ResetOffsetCommand { get; }

        // 断开连接逻辑
        private void Disconnect()
        {
            if (ConnectedDevice != null)
            {
                // 调用蓝牙服务断开连接
                _bluetoothService.Disconnect();

                // 清空已连接的设备信息
                ConnectedDevice = null;
            }
        }

        // 重置标点逻辑
        private void ResetOffset()
        {
            SensorData.ResetOffset();
        }

        // 启动传感器数据读取循环
        private void StartReadingSensorData()
        {
            Task.Run(async () =>
            {
                while (true)
                {
                    if (ConnectedDevice != null)
                    {
                        try
                        {
                            var newData = await _bluetoothService.ReadSensorDataAsync();
                            SensorData.UpdateSensorData(newData); // 调用实例方法
                        }
                        catch (Exception ex)
                        {
                            Console.WriteLine($"Error reading sensor data: {ex.Message}");
                        }
                    }
                    await Task.Delay(100); // 每100毫秒读取一次数据
                }
            });
        }
    }
}